var fn = {};
var LoginType = 1001;
/**
 * 获取Cookie值
 * @param {String} cname 获取的Cookie的名字
 */
fn.getCookie = function(cname) {//设置cookie
    if(!localStorage){
        // console.log('当前浏览器不支持本地存储');
        return undefined;
    }
    var _getObj = JSON.parse(localStorage[cname] ||'{}');
    return _getObj;
} 
// fn.getCookie = function(cname) {//读取cookie
//     var name = cname + "=";  
//     var ca = document.cookie.split(';');  
//     for(var i=0; i<ca.length; i++) {  
//         var c = ca[i];  
//         while (c.charAt(0)==' ') c = c.substring(1);  
//         if (c.indexOf(name) != -1) return JSON.parse(c.substring(name.length, c.length));  
//     }  
//     return {};  
// }

/**
 * 设置Cookie的值
 * @param {String} cname Cookie的名字
 * @param {Object} cvalue Cookie的值
 * @param {Int} exdays Cookie的有效时间默认为0，不清楚Cookie
 */
fn.setCookie = function(cname, cvalue) {//设置cookie
    if(!localStorage){
        // console.log('当前浏览器不支持本地存储');
        return undefined;
    }
    localStorage[cname] = JSON.stringify(cvalue);
} 
// fn.setCookie = function(cname, cvalue, exdays) {//设置cookie
//     cvalue = JSON.stringify(cvalue);
//     var d = new Date();  
//     d.setTime(d.getTime() + (exdays*24*60*60*1000));  
//     var expires = "expires="+d.toUTCString();  
//     document.cookie = cname + "=" + cvalue + "; " + expires;  
// } 

//格式化字符串头尾的空白字符
fn.Trim = function(str, is_global) {
    var result;
    try{
        result = str.replace(/(^\s+)|(\s+$)/g, "");
        if (is_global.toLowerCase() == "g") {
            result = result.replace(/\s/g, "");
        }
        return result;
    }catch(e){
        return '';
    }
} 


fn.formatDate = function(date, fmt) {
	if (/(y+)/.test(fmt)) {
		fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
	}
	let o = {
		'M+': date.getMonth() + 1,
		'd+': date.getDate(),
		'h+': date.getHours(),
		'm+': date.getMinutes(),
		's+': date.getSeconds()
	}
	for (let k in o) {
		if (new RegExp(`(${k})`).test(fmt)) {
			let str = o[k] + ''
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str))
		}
	}
	return fmt
}
function padLeftZero(str) {
	return ('00' + str).substr(str.length)
}

/**本地存储:聊天用户信息
 * 读取全部聊天用户信息
 * 读取指定用户聊天信息
 * 添加用户
 * 删除用户
 * 添加用户聊天信息
 * 修改新消息数量
 * 清空用户消息
 */

/**
 * 获取用户聊天信息
 * @param {Int} user_id 可选,获取指定的的聊天信息，填写则获取全部用户的聊天信息
 */
fn.getMsgList = function(cs_user,user_id){//获取本地会话记录
    if(!localStorage){
        // console.log('当前浏览器不支持本地存储');
        return undefined;
    }
    var MsgList = JSON.parse(localStorage.MsgList ||'{}');
    if(MsgList.list == undefined){
        MsgList.list = {};
    }
    if(!(cs_user in MsgList.list)){
        MsgList.list[cs_user] = [];
    }
    var userIndex = null;
    if(user_id){
        MsgList.list[cs_user].some(function(item,index){
            if(item.user_id == parseInt(user_id)){
                userIndex = index;
                return true;
            }
            return false;
        });
        if(userIndex != null){
            return MsgList.list[cs_user][userIndex];
        }
        return userIndex;
    }
    return MsgList.list[cs_user];
}



/**
 * 添加用户
 */
fn.updataMsgList = function(cs_user,user_id,user){//获取本地会话记录
    if(!localStorage){
        // console.log('当前浏览器不支持本地存储');
        return undefined;
    }
    var MsgList = JSON.parse(localStorage.MsgList ||'{}');
    if(MsgList.list == undefined){
        MsgList.list = {};
    }
    if(!(cs_user in MsgList.list)){
        MsgList.list[cs_user] = [];
    }
    var userIndex = null;
    MsgList.list[cs_user].some(function(item,index){
        if(item.user_id == user_id){
            userIndex = index;
            return true;
        }
        return false;
    });
    if(userIndex != null){
        MsgList.list[cs_user][userIndex] = user;
        localStorage.MsgList = JSON.stringify(MsgList);
        return {status:1,msg:'修改成功'};
    }else{
        return {status:-1,msg:'用户不存在'};
    }
    
}

/**
 * 添加用户
 */
fn.addMsgList = function(cs_user,user){
    if(!localStorage){
        // console.log('当前浏览器不支持本地存储');
        return undefined;
    }
    var MsgList = JSON.parse(localStorage.MsgList || '{}');
    if(MsgList.list == undefined){
        MsgList.list = {};
    }
    if(!(cs_user in MsgList.list)){
        MsgList.list[cs_user] = [];
    }

    if(fn.getMsgList(cs_user,user.user_id) == undefined){
        MsgList.list[cs_user].push(user);
        localStorage.MsgList = JSON.stringify(MsgList);
        return 'success';
    }else{
        //当前用户已存在
        return undefined;
    }
}


/**
 * 添加用户聊天记录
 */
fn.addUserMsgList = function(cs_user,user_id,msg){
    if(!localStorage){
        // console.log('当前浏览器不支持本地存储');
        return undefined;
    }
    var MsgList = JSON.parse(localStorage.MsgList || '{}');
    var userIndex = null;
    MsgList.list[cs_user].some(function(item,index){
        if(item.user_id == user_id){
            userIndex = index;
            return true;
        }
        return false;
    });

    if(userIndex == null){
        return {status:-1,msg:'用户不存在'};
    }else{
        if(msg.send_type == LoginType){
            MsgList.list[cs_user][userIndex].new_msg_num = MsgList.list[cs_user][userIndex].new_msg_num || 0;
            MsgList.list[cs_user][userIndex].new_msg_num++;
        }
        MsgList.list[cs_user][userIndex].new_msg = {
            content: msg.type == 'text' ? msg.content :msg.type == 'image'?'[图片]':'[新消息]',
            time:msg.send_time,
        }
        MsgList.list[cs_user][userIndex].msg_list = MsgList.list[cs_user][userIndex].msg_list || [];
        MsgList.list[cs_user][userIndex].msg_list.push(msg);
        localStorage.MsgList = JSON.stringify(MsgList);
        return {status:1,msg:'添加成功',index:MsgList.list[cs_user][userIndex].msg_list.length - 1,list:MsgList.list[cs_user][userIndex]};
    }
}


fn.delMsgUser = function(cs_user,user){
    if(!localStorage){
        // console.log('当前浏览器不支持本地存储');
        return undefined;
    }
    var MsgList = JSON.parse(localStorage.MsgList || '{}');
    if(MsgList.list == undefined){
        MsgList.list = {};
    }
    if(!(cs_user in MsgList.list)){
        MsgList.list[cs_user] = [];
    }
    var userIndex = null;
    MsgList.list[cs_user].some(function(item,index){
        if(item.user_id == user.user_id){
            userIndex = index;
            return true;
        }
        return false;
    });

    if(userIndex == null){
        return {status:-1,msg:'用户不存在'};
    }else{
        MsgList.list[cs_user].splice(userIndex,1);
        localStorage.MsgList = JSON.stringify(MsgList);
        return {status:1,msg:'添加成功',list:MsgList.list[cs_user]};
    }
}




/**
 * 判断当前网页是否处在登陆状态
 * 1.获取班底cookie里的user和secret，有一个存在就返回为登陆 
 * 2.验证本地是否有cookie
 * 3.验证服务器的登陆用户与本地保存的登陆用户师是否一致
 */
fn.isLogin = function(callback){
    var _URL = $vm.App.URL;
    // fn.isLogin.getCookie('user')
    var cookie_user = fn.getCookie('user').id;
    var cookie_secret = fn.getCookie('secret');
    if(cookie_user == undefined || typeof $fn.getCookie('secret') != 'string'){
        //user和秘钥都不存在直接判定为登陆
        fn.setCookie('user',{});
        fn.setCookie('secret',{});
        callback(-1);
    }
    new Promise(function(success,error){
        $.post(_URL.node+'/isLogin',{user_id:cookie_user,key:cookie_secret,type:LoginType},function(res){
            success(res);
        })
    }).then((res)=>{//第一步完成
        if(res.status == 1){//服务是登陆状态
            var user = fn.getCookie('user');//获取本地cookie保存的用户信息
            if(res.user_info.id == user.id){
                callback(1);
            }else{
                fn.setCookie('user',{});
                fn.setCookie('secret',{});
                fn.logOut({user_id:cookie_user,key:cookie_secret,type:LoginType});
                callback(-1);//服务器的登陆用户与本地保存的登陆用户不一致
            }
            return;
        }
        fn.setCookie('user',{});
        callback(-1);//服务器不是登陆状态
    });
}


/**
 * 退出登陆
 * 1.删除本地cookie
 */
fn.logOut = function(){
    fn.setCookie('user',{});
    fn.setCookie('secret',{});
}


/**
 * 登陆账号
 * @param {Object} data 用户名（username）和密码（pwd）
 * @param {function} callback 回调函数
 */
fn.login = function(data,callback){
    $.post(_URL.node+'/login',data,callback);
}












fn.getObjectURL = function(file) {
    var url = null;
    if (window.createObjectURL != undefined) { // basic
        url = window.createObjectURL(file);
    } else if (window.URL != undefined) { // mozilla(firefox)
        url = window.URL.createObjectURL(file);
    } else if (window.webkitURL != undefined) { // webkit or chrome
        url = window.webkitURL.createObjectURL(file);
    }
    return url;
}




fn.get_URL = function(locationTest){
    var _URL = {};
    if(locationTest){
        _URL.server='https://wechat.shangning.site';
        _URL.node='https://node2.shangning.site';
        _URL.wss='wss://node2.shangning.site';
    }else{
        _URL.server='https://sn.shangning.site';
        _URL.node='https://node.shangning.site';
        _URL.wss='wss://node.shangning.site';
    }
    window._URL = _URL;
    return _URL;
}

fn.getLoginType = function(){
    return LoginType;
}

export { fn };